package com.fastadmin.config.security.simple;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.fastadmin.common.FAConst;
import com.fastadmin.common.cookie.CookieUtils;
import com.fastadmin.common.jedis.JedisTemplate;
import com.fastadmin.common.mapper.JsonMapper;
import com.fastadmin.mapper.impl.UserMapper;
import com.fastadmin.pojo.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

import static com.fastadmin.common.FAConst.LoginConst.*;

/**登录成功
 * @author YangKun
 * @date 2019/3/12.
 */
public class LoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private RsaSigner signer;
    private JedisTemplate jedisTemplate;
    private UserMapper userMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        String userJsonStr = JSON.toJSONString(authentication.getPrincipal());
        //做一点登录之外的东西

        UserDetails user = (UserDetails) authentication.getPrincipal();
        User DB_USER = userMapper.findByUsername(user.getUsername());
        jedisTemplate.Setex(REDIS_USER_PREFIX + DB_USER.getUsername(), JSONUtil.toJsonStr(DB_USER), REDIS_USER_TIME);

        String token = JwtHelper.encode(userJsonStr, signer).getEncoded();
        CookieUtils.setCookie(request, response, COOKIE_NAME, token, REDIS_USER_TIME);


        Map<Object, Object> build = MapUtil.builder()
                .put("code", 1)
                .put("msg", "ok")
                .put("data", DB_USER)
                .build();
        /*response.sendRedirect("/admin/home/index");*/
        response.getWriter().println(JsonMapper.nonDefaultMapper().toJson(build));
    }

    public void setSigner(RsaSigner signer) {
        this.signer = signer;
    }

    public void setJedisTemplate(JedisTemplate jedisTemplate) {
        this.jedisTemplate = jedisTemplate;
    }

    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }
}
